package com.itheima.web.client;

import com.github.pagehelper.PageInfo;
import com.itheima.model.domain.Article;
import com.itheima.model.domain.Comment;
import com.itheima.service.IArticleService;
import com.itheima.service.ISiteService;
import com.itheima.service.impl.CommentServiceImpl;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequiredArgsConstructor
@RequestMapping("/article")
@Slf4j
public class ArticleController {
    private final IArticleService articleService;
    private final ISiteService siteService;
    private final CommentServiceImpl commentServiceImpl;

    @GetMapping("/{id}")
    public String article(HttpServletRequest request, @PathVariable("id") Integer id) {
        Article article = articleService.selectArticleById(id);
        if(article!=null){
            // 查询封装评论相关数据
            getArticleComments(request, article);
            // 更新文章点击量
            siteService.updateStatistics(article);
            request.setAttribute("article",article);
            return "client/articleDetails";
        }else{
            log.warn("查询文章详情结果为空，查询文章id: "+id);
            return "comm/error_404";
        }
    }

    // 查询文章的评论信息，并补充到文章详情里面
    private void getArticleComments(HttpServletRequest request, Article article) {
        if(article.getAllowComment()){
            // cp表示评论页码，commentPage
            String cp = request.getParameter("cp");
            cp = StringUtils.isBlank(cp) ? "1" : cp;
            request.setAttribute("cp",cp);
            PageInfo<Comment> comments =
                    commentServiceImpl.getComments(article.getId(), Integer.parseInt(cp), 3);
            request.setAttribute("cp", cp);
            request.setAttribute("comments", comments);
        }
    }

}
